<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>设备管理</span>
        </div>
      </template>
      
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="设备名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择设备类型" clearable>
            <el-option
              v-for="dict in typeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['qep:equipment:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['qep:equipment:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['qep:equipment:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['qep:equipment:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备ID" align="center" prop="id" />
        <el-table-column label="设备名称" align="center" prop="name" />
        <el-table-column label="设备型号" align="center" prop="model" />
        <el-table-column label="设备类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="typeOptions" :value="getCleanedValue(scope.row.type)" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="statusOptions" :value="getCleanedValue(scope.row.status)" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['qep:equipment:edit']"
            >修改</el-button>
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleView(scope.row)"
              v-hasPermi="['qep:equipment:query']"
            >查看</el-button>
            <el-button
              link
              type="primary"
              icon="Tools"
              @click="handleCalibration(scope.row)"
              v-hasPermi="['qep:calibration:list']"
            >校准记录</el-button>
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['qep:equipment:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="equipmentForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择设备类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment, exportEquipment } from '@/api/qep/equipment';
import { getDicts } from '@/api/system/dict/data';
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { parseTime } from '@/utils/ruoyi';
import { download } from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

// Helper to extract the actual value if it's an array or JSON string array
const getCleanedValue = (val) => {
  if (val === null || typeof val === 'undefined') {
    return undefined;
  }
  
  // 如果是数组，直接取第一个元素
  if (Array.isArray(val)) {
    return val.length > 0 ? String(val[0]) : undefined;
  }
  
  // 如果是字符串，尝试解析为JSON
  if (typeof val === 'string') {
    // 如果字符串看起来像JSON数组
    if (val.startsWith('[') && val.endsWith(']')) {
      try {
        const parsed = JSON.parse(val);
        if (Array.isArray(parsed) && parsed.length > 0) {
          return String(parsed[0]);
        }
      } catch (e) {
        // 解析失败，返回原始字符串
      }
    }
  }
  
  // 其他情况，返回字符串形式
  return String(val);
};

const router = useRouter();
const { proxy } = getCurrentInstance();

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 设备表格数据
const equipmentList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 设备类型选项
const typeOptions = ref([]);
// 设备状态选项
const statusOptions = ref([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  type: undefined
});

// 表单参数
const form = reactive({
  id: undefined,
  name: undefined,
  model: undefined,
  type: undefined,
  status: "0",
  description: undefined
});

// 表单校验
const rules = reactive({
  name: [
    { required: true, message: "设备名称不能为空", trigger: "blur" }
  ],
  model: [
    { required: true, message: "设备型号不能为空", trigger: "blur" }
  ],
  type: [
    { required: true, message: "设备类型不能为空", trigger: "change" }
  ]
});

onMounted(() => {
  // 获取字典数据
  Promise.all([
    getDicts("qep_equipment_type"),
    getDicts("sys_normal_disable")
  ]).then(([typeResponse, statusResponse]) => {
    typeOptions.value = typeResponse.data;
    statusOptions.value = statusResponse.data;
    console.log("设备类型选项加载完成:", JSON.stringify(typeOptions.value));
    console.log("状态选项加载完成:", JSON.stringify(statusOptions.value));
    // 字典数据加载完成后获取设备列表
    getList();
  }).catch(error => {
    console.error("加载字典数据失败:", error);
    // 即使字典加载失败，也尝试获取设备列表
    getList();
  });
});

/** 查询设备列表 */
function getList() {
  loading.value = true;
  listEquipment(queryParams).then(response => {
    equipmentList.value = response.rows;
    console.log(response.rows);
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.id = undefined;
  form.name = undefined;
  form.model = undefined;
  form.type = undefined;
  form.status = "0";
  form.description = undefined;
  proxy.resetForm("equipmentForm");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0];
  getEquipment(id).then(response => {
    const fetchedData = response.data;
    
    // 打印原始数据，用于调试
    console.log("原始设备数据:", JSON.stringify(fetchedData));
    console.log("原始设备类型:", JSON.stringify(fetchedData.type));
    console.log("原始设备状态:", JSON.stringify(fetchedData.status));
    
    // Assign cleaned values to the form
    form.id = fetchedData.id;
    form.name = fetchedData.name;
    form.model = fetchedData.model;
    form.type = getCleanedValue(fetchedData.type);
    form.status = getCleanedValue(fetchedData.status);
    form.description = fetchedData.description;
    
    // 打印处理后的数据，用于调试
    console.log("处理后的设备类型:", form.type);
    console.log("处理后的设备状态:", form.status);
    console.log("可用的设备类型选项:", JSON.stringify(typeOptions.value));
    console.log("可用的设备状态选项:", JSON.stringify(statusOptions.value));
    
    // 确保设备类型和状态值在选项中存在
    const typeExists = typeOptions.value.some(option => option.value === form.type);
    if (!typeExists && typeOptions.value.length > 0) {
      console.log("设备类型值不在选项中，使用第一个选项值");
      form.type = typeOptions.value[0].value;
    }

    // 确保状态值是字符串类型
    if (form.status !== undefined) {
      form.status = String(form.status);
      console.log("转换后的设备状态值:", form.status);
    }
    
    open.value = true;
    title.value = "修改设备";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["equipmentForm"].validate(valid => {
    if (valid) {
      // 确保提交前数据类型正确
      const submitData = { ...form };
      
      // 确保类型和状态是字符串而非数组
      if (submitData.type) {
        submitData.type = String(submitData.type);
      }
      
      if (submitData.status) {
        submitData.status = String(submitData.status);
      }
      
      console.log("提交数据:", JSON.stringify(submitData));
      
      if (form.id) {
        updateEquipment(submitData).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEquipment(submitData).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const equipmentIds = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除设备编号为"' + equipmentIds + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    return delEquipment(equipmentIds);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  // 创建一个新的查询参数对象，避免引用错误
  const exportParams = {
    name: queryParams.name,
    type: queryParams.type
  };
  
  ElMessageBox.confirm('是否确认导出所有设备数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    return exportEquipment(exportParams);
  }).then(response => {
    proxy.$download.excel(response, `设备数据_${new Date().getTime()}.xlsx`);
  }).catch((error) => {
    console.error('导出失败:', error);
  });
}

/** 查看按钮操作 */
function handleView(row) {
  const id = row.id;
  router.push({ path: '/equipment/detail', query: { id: id } });
}

/** 校准记录按钮操作 */
function handleCalibration(row) {
  const id = row.id;
  router.push({ path: '/equipment/calibration', query: { equipmentId: id } });
}
</script> 